<style scoped lang="less">
.bg {
  background: #ffffff;
  padding: 10px;
  border-radius: 6px;
}
.queryLabel {
  font-weight: bold;
  font-size: 16px;
  font-color: #464c5b;
  text-align: left;
  padding: 6px;
}
.queryInput {
  flex: 0 0 300px;
  border: 1px solid #57a3f3;
  border-radius: 4px;
}
.queryBtn {
  background: #57a3f3;
  margin: -6px -9px;
}
.queryGroupBtnContain {
  text-align: left;
  padding-top: 4px;
}
.navItem {
  padding: 6px;
}
.contentCol {
  border: 1px solid #eee;
  border-radius: 4px;
  float: right;
}
.cardItem {
  padding: 0;
  min-width: 300px;
  float: left;
  margin: 4px;
}
.itemContain {
  display: flex;
  .itemLeft {
    flex: 0 0 60px;
    .leftIcon {
      background: #f3a97f;
    }
    .leftText {
      font-size: 14px;
      color: #9ea7b4;
      padding: 0;
    }
  }
  .itemRight {
    flex: 1;
    border-left: 1px solid #eee;
    .rightItemContain {
      color: #9ea7b4;
      display: flex;
      justify-content: space-between;
      .rightNumber {
        color: #f3a97f
      }
      .rightIcon {
        padding-top: 4px;
      }
    }
  }
}
.treeContain {
  min-height: 500px;
}
.cardRow {
  margin: 4px;
  width: 350px;
  height: 180px;
  float: left;
  border: solid 1px #d7d7d7;
  border-radius: 4px;
}
.cardRow:hover {
  background: #f6f6f6;
  box-shadow: 0 1px 6px rgba(0, 0, 0, 0.47);
}
.rowInfo {
  padding: 4px;
  min-height: 500px;
}

</style>
<template>
  <Row>
    <Card dis-hover>
      <!-- 搜索部分 -->
      <div slot="title">
        <div class="queryLabel">空间管理</div>
        <Input v-model="queryObj.str" placeholder="请输入搜索内容" class="queryInput">
        <Button slot="append" icon="ios-search" type="info" class="queryBtn"> 搜索</Button>
        </Input>
        <div class="queryGroupBtnContain">
          <Button type="text">涂装</Button>
          <Button type="text">HD1</Button>
          <Button type="text">焊装</Button>
          <Button type="text">树脂</Button>
          <Button type="text">公用动力</Button>
          <Button type="text">总装</Button>
        </div>
      </div>
      <!-- 展示部分 -->
      <Row>
        <Col span="8" class="treeContain">
        <Tree v-if="iviewtreeShow" :data="treeData" :render="renderContent"></Tree>
        <Spin size="large" fix v-if="!iviewtreeShow"></Spin>
        </Col>
        <Col span="16" class="contentCol">
        <div class="navItem">
          <Breadcrumb class="BreadcrumbContain">
            <BreadcrumbItem v-for="(item,index) in queryNaviTextData" :key=" 'sd'+index ">{{item}}</BreadcrumbItem>
          </Breadcrumb>
        </div>
        <Row class="rowInfo">
          <Col span="6" v-for="(item, index) in spaceDeviceData" :key="'sd'+index" class="cardRow">
          <!--组件化-->
          <DataCard :card-data="item"></DataCard>
          </Col>
          <Spin size="large" fix v-if="spaceDeviceObj.isRequest"></Spin>
          <Alert type="warning" show-icon v-show="!spaceDeviceObj.hasData">无设备信息！
            <template slot="desc"></template>
          </Alert>
        </Row>
        </Col>
      </Row>
    </Card>
    <Modal v-model="auModalObj.showModal" :title="auModalObj.modalTitle">
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        <FormItem label="节点名称" prop="title">
          <Input v-model="formValidate.title" placeholder="请输入节点名称"></Input>
        </FormItem>
        <FormItem label="节点类型" prop="title">
          <Select v-model="formValidate.type">
            <Option v-for="item in spaceType" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click.native="auModalObj.noClick">取消</Button>
        <Button type="primary" @click.native="auModalObj.yesClick">确认</Button>
        <!-- :loading="modal_loading" -->
      </div>
    </Modal>
  </Row>
</template>
<script>
import DataCard from '../modules/DataCard'
export default {
  components: { DataCard },
  data: function () {
    let self = this
    // 新增or编辑节点
    let auModalObj = {
      showModal: false,
      modalTitle: '',
      show: function () {
        auModalObj.showModal = true
        return auModalObj
      },
      hide: function () {
        auModalObj.showModal = false
        return auModalObj
      },
      input: '',
      temFunc: function () {},
      yes: function (func) {
        auModalObj.temFunc = func
        return auModalObj
      },
      yesClick: function () {
        self.$refs['formValidate'].validate((valid) => {
          if (valid) {
            // self.$Message.success('Success!')
            auModalObj.showModal = false
            auModalObj.temFunc()
            return auModalObj
          } else {
            // self.$Message.error('Fail!')
          }
        })
      },
      noClick: function () {
        auModalObj.showModal = false
        return auModalObj
      }
    }
    return {
      iviewtreeShow: false,
      rootTitle: '',
      pageIndex: 0,
      tableList: [],
      treeData: [],
      spaceType: [
        {'value': 1, 'label': '总部'},
        {'value': 2, 'label': '工厂'},
        {'value': 3, 'label': '车间'},
        {'value': 4, 'label': '生产线'}
      ],
      buttonProps: {
        type: 'ghost',
        size: 'small'
      },
      modalEditAdd: {
        show: false,
        title: ''
      },
      formValidate: {
        title: '',
        type: 1
      },
      ruleValidate: {
        title: [{ required: true, message: '必填项！', trigger: 'blur' }, { max: 10, message: '最多10个字！', trigger: 'change' }]
      },
      temData: {},
      queryObj: {},
      itemObj: {},
      addItemObj: {},
      updateItemObj: {},
      auModalObj: auModalObj,
      queryNaviTextData: [],
      spaceDeviceData: [],
      spaceDeviceObj: {
        hasData: true,
        isRequest: true
      }
    }
  },
  created: function () {
    this.list()
  },
  mounted: function () {},
  destroyed: function () {
    this.$Message.destroy()
  },
  methods: {
    // 渲染根节点
    renderRoot: function (h, { root, node, data }) {
      let self = this
      return h('span', {
        style: {
          display: 'inline-block',
          width: '100%'
        }
      }, [
        h('span', [
          h('Icon', {
            props: {
              type: 'ios-folder-outline'
            },
            style: {
              marginRight: '8px'
            }
          }),
          h('div', {
            style: {
              display: 'inline-block',
              borderRadius: '8px',
              border: '1px solid grey',
              fontSize: '8px',
              padding: '0 4px',
              color: 'grey'
            }
          }, data.id),
          h('span', {
            attrs: {
              class: 'ivu-tree-title'
            },
            on: {
              click: (event) => {
                // 获取查询的级联导航
                self.getNaviText(data)
                // 选中样式
                let oneNode = document.querySelector('.ivu-tree-title-selected')
                if (oneNode) {
                  oneNode.classList.remove('ivu-tree-title-selected')
                }
                event.target.classList.add('ivu-tree-title-selected')
              }
            }
          }, data.title)
        ]),
        h('span', {
          style: {
            display: 'inline-block',
            float: 'right',
            marginRight: '32px'
          }
        }, [
          h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'md-add',
              type: 'primary'
            }),
            style: {
              width: '52px',
              marginRight: '18px'
            },
            on: {
              click: () => { this.append(data) }
            }
          })
        ])
      ])
    },
    // 渲染子节点
    renderContent: function (h, { root, node, data }) {
      let self = this
      if (data.title === self.rootTitle) {
        return this.renderRoot(h, { root, node, data })
      }
      return h('span', {
        style: {
          display: 'inline-block',
          width: '100%'
        }
      }, [
        h('span', [
          h('Icon', {
            props: {
              type: 'ios-paper-outline'
            },
            style: {
              marginRight: '8px'
            }
          }),
          h('div', {
            style: {
              display: 'inline-block',
              borderRadius: '8px',
              border: '1px solid grey',
              fontSize: '8px',
              padding: '0 4px',
              color: 'grey'
            }
          }, data.id),
          h('span', {
            attrs: {
              class: 'ivu-tree-title'
            },
            style: {
              verticalAlign: 'middle'
            },
            on: {
              click: (event) => {
                // 获取查询的级联导航
                self.getNaviText(data)
                // 选中样式
                let oneNode = document.querySelector('.ivu-tree-title-selected')
                if (oneNode) {
                  oneNode.classList.remove('ivu-tree-title-selected')
                }
                event.target.classList.add('ivu-tree-title-selected')
              }
            }
          }, data.title)
        ]),
        h('span', {
          style: {
            display: 'inline-block',
            float: 'right',
            marginRight: '32px'
          }
        }, [
          h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'md-add',
              type: 'default'
            }),
            style: {
              marginRight: '8px'
            },
            on: {
              click: () => { this.append(data) }
            }
          }),
          h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'md-remove',
              type: 'default'
            }),
            style: {
              marginRight: '8px'
            },
            on: {
              click: () => { this.remove(root, node, data) }
            }
          }),
          h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'md-create',
              type: 'default'
            }),
            on: {
              click: () => { this.edit(data) }
            }
          })
        ])
      ])
    },
    // 添加子节点
    append: function (data) {
      let self = this
      self.auModalObj.modalTitle = data.title + '新增节点'
      self.formValidate = {}
      self.formValidate.title = ''
      self.formValidate.type = data.type ? data.type + 1 : 1
      self.auModalObj.show().yes(function () {
        const children = data.children || []
        let title = self.formValidate.title
        children.push({
          title: title,
          expand: true
        })
        self.save(data, children, title)
        // self.$set(data, 'children', children)
      })
    },
    // 删除节点
    remove: function (root, node, data) {
      let self = this
      self.$Modal.confirm({
        title: data.title + '节点删除',
        content: '您确定删除节点：' + data.title + '，该操作会取消跟该空间关联的设备，以及删除所有子级空间!',
        onOk: () => {
          self.deleteMore(root, node, data)
        },
        okText: '确定',
        cancelText: '取消',
        onCancel: () => {
          console.log('取消删除')
          this.$Message.info('取消删除')
        }
      })
    },
    // 编辑节点
    edit: function (data) {
      let self = this
      self.auModalObj.modalTitle = data.title + '编辑节点'
      self.formValidate = data
      self.auModalObj.show().yes(function () {
        let title = self.formValidate.title
        self.upd(data, title)
        // self.$set(data, 'title', title)
      })
    },
    // 获取树数据list
    list: function () {
      let self = this
      let getData = {
        'page': self.pageIndex,
        'searchParam': self.queryStr
      }
      self.tableList = []
      window.myapi.space_list(getData).then(function (res) {
        if (res.data.status === 200) {
          self.tableList = res.data.data.content
          self.treeReady(res.data.data.content)
        } else {
          let msg = res.data.msg ? res.data.msg : '请求数据失败!'
          self.$Message.error({ content: msg, duration: 5, closable: true })
        }
      }).catch(function (e) {
        if (e && e.response && e.response.data) {
          let msg = e.response.data.message ? e.response.data.message : '请求数据失败!'
          self.$Message.error({ content: msg, duration: 5, closable: true })
        }
      })
    },
    // 树数据处理为标准格式
    treeReady: function (arr) {
      let self = this
      let one = self.treeRoot(arr)
      // 标准化的数据才不会有问题
      let standardOne = self.standardData(one)
      self.treeData.push(standardOne)
      self.iviewtreeShow = true
    },
    // 提取树 根节点
    treeRoot: function (arr) {
      let self = this
      let len = arr.length
      for (let i = 0; i < len; i++) {
        if (arr[i].parentId === 0) {
          arr[i].children = []
          arr[i].title = arr[i].name
          arr[i].expand = true
          self.queryNaviTextData = []
          self.queryNaviTextData.push(arr[i].name)
          self.spaceInfo(arr[i].id)
          self.rootTitle = arr[i].name
          return self.treeNode(arr, arr[i])
        }
      }
    },
    // 提取树 子节点
    treeNode: function (arr, one) {
      let self = this
      let len = arr.length
      one.children = []
      for (let i = 0; i < len; i++) {
        if (one.id === arr[i].parentId) {
          arr[i].children = []
          arr[i].title = arr[i].name
          arr[i].expand = true
          one.children.push(self.treeNode(arr, arr[i]))
        }
      }
      return one
    },
    // 把树数据标准化
    standardData: function (one) {
      let self = this
      let len = one.children.length
      let oneTem = {}
      oneTem.title = one.title
      oneTem.expand = true
      oneTem.id = one.id
      oneTem.parentId = one.parentId
      oneTem.type = one.type
      oneTem.children = []
      for (let i = 0; i < len; i++) {
        oneTem.children.push(self.standardData(one.children[i]))
      }
      return oneTem
    },
    // 重置form
    handleReset: function (name) {
      this.$refs[name].resetFields()
    },
    // 新增 节点
    save: function (data, children, title) {
      let self = this
      let postData = {
        name: title,
        type: this.formValidate.type,
        parentId: data.id,
        remark: title
      }
      window.myapi.space_save(postData).then(function (res) {
        if (res.data.status === 200) {
          self.$Message.success('新增成功!')
          children.forEach((item) => {
            if (item.id === undefined || item.id === null || item.id === '') {
              item.id = res.data.data.id
            }
          })
          self.$set(data, 'children', children)
        } else {
          let msg = res.data.msg ? res.data.msg : '新增失败！'
          self.$Message.error(msg)
        }
      }).catch(function (e) {
        if (e && e.response && e.response.data) {
          let msg = e.response.data.message ? e.response.data.message : '新增失败!'
          self.$Message.error({ duration: 0, closable: true, content: msg })
        }
      }).finally(() => {
        this.formValidate = {
          title: '',
          type: 1
        }
        // 更新缓存
        this.loadInitSpacesData()
      })
    },
    // 修改 节点
    upd: function (data, title) {
      let self = this
      let postData = {
        id: data.id,
        parentId: data.parentId,
        name: this.formValidate.title,
        remark: this.formValidate.remark,
        type: this.formValidate.type
      }
      window.myapi.space_upd(postData).then(function (res) {
        if (res.data.status === 200) {
          self.$Message.success('修改成功!')
          self.$set(data, 'title', title)
        } else {
          let msg = res.data.msg ? res.data.msg : '修改失败！'
          self.$Message.error(msg)
        }
      }).catch(function (e) {
        if (e && e.response && e.response.data) {
          let msg = e.response.data.message ? e.response.data.message : '修改失败!'
          self.$Message.error({ duration: 0, closable: true, content: msg })
        }
      }).finally(() => {
        // 更新缓存
        this.loadInitSpacesData()
      })
    },
    // 删除 节点
    deleteMore: function (root, node, data) {
      let self = this
      let postData = []
      postData.push(data.id)
      window.myapi.space_del(postData).then(function (res) {
        if (res.data.status === 200) {
          self.$Message.success('删除成功!')
          const parentKey = root.find(el => el === node).parent
          const parent = root.find(el => el.nodeKey === parentKey).node
          const index = parent.children.indexOf(data)
          parent.children.splice(index, 1)
        } else {
          let msg = res.data.msg ? res.data.msg : '删除失败!'
          self.$Message.error(msg)
        }
      }).catch(function (e) {
        if (e && e.response && e.response.data) {
          let msg = e.response.data.message ? e.response.data.message : '删除失败!'
          self.$Message.error({ duration: 0, closable: true, content: msg })
        }
      }).finally(() => {
        // 更新缓存
        this.loadInitSpacesData()
      })
    },
    loadInitSpacesData () {
      // 加载空间数据
      window.myapi.space_tree().then(res => {
        if (res.data.status === 200) {
          this.$store.commit('addSpaces', res.data.data)
        } else {
          this.$Message.error(res.data.msg)
        }
      }).catch(function (e) {
        console.log('catch wrong ,,,,,,,,')
      })
    },
    // 查询单个实体 节点
    spaceInfo: function (id) {
      let self = this
      let postData = { 'id': id }
      self.spaceDeviceObj.isRequest = true
      self.spaceDeviceData = []
      window.myapi.dev_sid(postData).then(function (res) {
        self.spaceDeviceObj.isRequest = false
        if (res.data.status === 200) {
          self.spaceDeviceData = res.data.data
          if (self.spaceDeviceData.length === 0) {
            self.spaceDeviceObj.hasData = false
          } else {
            self.spaceDeviceObj.hasData = true
          }
        } else {
          let msg = res.data.msg ? res.data.msg : '请求失败!'
          self.$Message.error(msg)
          self.spaceDeviceObj.hasData = false
        }
      }).catch(function (e) {
        self.spaceDeviceObj.isRequest = false
        if (e && e.response && e.response.data) {
          let msg = e.response.data.message ? e.response.data.message : '请求失败!'
          self.$Message.error({ duration: 0, closable: true, content: msg })
          self.spaceDeviceObj.hasData = false
        }
      })
    },
    // 获取查询的导航
    getNaviText: function (data) {
      let self = this
      if (data.parentId === 0) {
        // 点击根节点
        self.queryNaviTextData = []
        self.queryNaviTextData.push(data.title)
      } else {
        // 子节点
        let txt = self.parentId2title(data.parentId)
        txt = txt.substring(0, txt.length - 1)
        let txtArr = txt.split(',')
        txtArr.reverse()
        txtArr.push(data.title)
        self.queryNaviTextData = txtArr
      }
      // 查询信息
      self.spaceInfo(data.id)
    },
    // parentId对应的title
    parentId2title: function (parentId) {
      let self = this
      let len = self.tableList.length
      for (let i = 0; i < len; i++) {
        if (parentId.toString() === self.tableList[i].id.toString()) {
          return self.tableList[i].title + ',' + self.parentId2title(self.tableList[i].parentId)
        }
      }
      return ''
    }
  }
}

</script>
